package com.usian.article.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.usian.article.article.mapper.ApArticleConfigMapper;
import com.usian.article.article.mapper.ApArticleContextMapper;
import com.usian.article.article.mapper.ApArticleMapper;
import com.usian.article.article.mapper.ArticleMapper;
import com.usian.article.article.service.ArticleHomeService;
import com.usian.common.article.ArticleConstans;
import com.usian.model.article.ArticleHomeDto;
import com.usian.model.article.ArticleInfoDto;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class ArticleHomeServiceImpl implements ArticleHomeService {
    private final Integer SIZE=50;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Resource
    ApArticleConfigMapper apArticleConfigMapper;

    @Resource
    ApArticleContextMapper apArticleContextMapper;

    @Override
    public ResponseResult load(ArticleHomeDto dto, Integer type) {
        //判定参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        int min=Math.min(dto.getSize(),SIZE);
        //判定类型
        if(!type.equals(ArticleConstans.LOADTYPE_LOAO_MORE)&&!type.equals(ArticleConstans.LOADTYPE_LOAO_New)){
            type=ArticleConstans.LOADTYPE_LOAO_MORE;
        }

        if(dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        if(dto.getMaxBehotTime()==null){
            dto.setMaxBehotTime(new Date());
        }
        List<ApArticle> load = apArticleMapper.load(dto, type,min);
        return ResponseResult.okResult(load);
    }

    @Override
    public ResponseResult loadNewsByid(ArticleInfoDto dto) {
        //校验参数
        if(dto==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //根据id进行查询article_config
        com.usian.model.article.pojos.ApArticleConfig apArticleConfig=apArticleConfigMapper.findByid(dto.getArticleId());

        LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleContent::getArticleId,dto.getArticleId());
        //根据id进行查询article_context
        ApArticleContent apArticleContent = apArticleContextMapper.selectOne(queryWrapper);

        //封装结果返回
        HashMap<String, Object> map = new HashMap<>();
        map.put("config",apArticleConfig);
        map.put("content",apArticleContent);
        return ResponseResult.okResult(map);
    }
}
